package com.myorg.search.condition;

import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class SearchCondition {
	public final static int OFF_SET = 20;
	private Pattern pattern = null;
	private String key = null;

	public static SearchCondition parse(String s) {
		if (StringUtils.isEmpty(s)) {
			return null;
		}

		String s2 = s.trim().toUpperCase();

		int index = s2.indexOf(" OR ");
		if (index != -1) {
			String left = s.substring(0, index).trim();
			String right = s.substring(index + " OR ".length()).trim();
			if (StringUtils.isNotEmpty(left) && StringUtils.isNotEmpty(right)) {
				return new OrCondition(parse(left), parse(right));
			}
		}

		index = s2.indexOf(" AND ");
		if (index != -1) {
			String left = s.substring(0, index).trim();
			String right = s.substring(index + " AND ".length()).trim();
			if (StringUtils.isNotEmpty(left) && StringUtils.isNotEmpty(right)) {
				return new AndCondition(parse(left), parse(right));
			}
		}

		if (s2.startsWith("NOT ")) {
			String base = s.substring("NOT ".length()).trim();
			if (StringUtils.isNotEmpty(base)) {
				return new NotCondition(parse(base));
			}
		}

		SearchCondition rtn = new SearchCondition();
		if (s.contains("?")) {
			rtn.pattern = Pattern.compile(s);
		} else if (s.contains("[") && s.contains("]")) {
			rtn.pattern = Pattern.compile(s);
		} else if (s.contains("{") && s.contains("}")) {
			rtn.pattern = Pattern.compile(s);
		} else if (s.contains("\\")) {
			rtn.pattern = Pattern.compile(s);
		} else if (s.contains("+")) {
			rtn.pattern = Pattern.compile(s);
		} else if (s.contains("^")) {
			rtn.pattern = Pattern.compile(s);
		} else if (s.contains("$")) {
			rtn.pattern = Pattern.compile(s);
		} else if (s.contains("|")) {
			rtn.pattern = Pattern.compile(s);
		} else if (s.startsWith("/") && s.endsWith("/")) {
			rtn.pattern = Pattern.compile(s.substring(1, s.length() - 1));
		} else if (s.contains("*")) {
			rtn.pattern = Pattern.compile(s.replace("*", ".*"));
		} else {
			rtn.key = s.toUpperCase().trim();
		}

		return rtn;
	}

	public String matchAndSummarize(String s) {
		if (s == null) {
			return null;
		}

		if (key != null && StringUtils.containsIgnoreCase(s, key)) {
			String s2 = s.toUpperCase();
			int index = s2.indexOf(key);
			if (index != -1) {
				int begin = index - OFF_SET;
				if (begin < 0) {
					begin = 0;
				}
				int end = index + OFF_SET;
				if (end > s.length()) {
					end = s.length();
				}
				return (begin == 0 ? "" : "...") + s.substring(begin, end) + (end == s.length() ? "" : "...");
			}
		}

		if (pattern != null) {
			if (pattern.matcher(s).find()) {
				int end = OFF_SET * 2 > s.length() ? s.length() : OFF_SET * 2;
				return s.substring(0, end) + (end == s.length() ? "" : "...");
			}
		}

		return null;
	}
}
